package com.kamilparzych.pl.manageMyCost.logic;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.kamilparzych.pl.manageMyCost.data.CostEntry;

public class CostEntryTool {
	
	private static final String URI_PREFIX = "http://chart.apis.google.com/chart";
	
	private List<CostEntry> entries;

	public CostEntryTool(List<CostEntry> entries) {
		super();
		this.entries = entries;
	}
	
	public String evaluateSimpleURI() {
		final StringBuilder ret = new StringBuilder();

		final StringBuilder chd = new StringBuilder("&chd=t:");
		final StringBuilder chl = new StringBuilder("&chl=");
		
		Map<String, Float> costData = new HashMap<String, Float>();
		
		for(final CostEntry costEntry : entries) {
			if (costData.containsKey(costEntry.getType())) {
				Float tmp = costData.get(costEntry.getType());
				tmp += Float.parseFloat(costEntry.getCost());
				costData.put(costEntry.getType(), tmp);
			} else {
				costData.put(costEntry.getType(), Float.parseFloat(costEntry.getCost()));
			}
		}
		
		for(final String key : costData.keySet()) {
			chl.append(key)
			   .append("|");
			chd.append(costData.get(key))
			   .append(",");
		}

		chd.deleteCharAt(chd.length()-1);
		chl.deleteCharAt(chl.length()-1);
		
		ret.append(URI_PREFIX)
		   .append("?cht=p3")
		   .append("&chs=400x160")
		   .append(chd.toString())
		   .append(chl.toString());

		return ret.toString();
	}
	
	public String toCsv() {
		final StringBuilder ret = new StringBuilder();
		
		for (final CostEntry costEntry : entries) {
			ret.append(costEntry.getType()).append(",")
			   .append(costEntry.getCost()).append(",")
			   .append(costEntry.getDesc()).append(",")
			   .append((new SimpleDateFormat("yyyy/MM/dd")).format(costEntry.getDate())).append("<br />");
		}
		return ret.toString();
	}
	
	public String toHTMLTable() {
		final StringBuilder ret = new StringBuilder();
		
		ret.append("<table border=\"1\">");
		for (final CostEntry ce : entries) {
			ret.append("<tr>")
			   .append("<td>").append(ce.getType()).append("</td>")
			   .append("<td>").append(ce.getCost()).append("</td>")
			   .append("<td>").append(ce.getDesc()).append("</td>")
			   .append("<td>").append(new SimpleDateFormat("yyyy/MM/dd").format(ce.getDate())).append("</td>")
			   .append("</tr>");
		}
		ret.append("</table>");
		
		return ret.toString();
	}

}
